<template>
  <div class="dc-container dc-main" v-loading="loading">
    <history ref="history" :bussObject="curentRow"></history>
    <edit-form ref="editForm" :permission="permission" @save-finished="getList" @before-load="setLoad" @after-load="resetLoad"></edit-form>
    <el-row :gutter="0" justify="start" align="top">
      <el-col :span="19">
        <query-tag ref="queryTag" v-model="queryEditObject"
          :moreParm="moreParm" :routerId="$route && $route.meta.routerId" :isConditionPanel="isConditionPanel"
          @queryTagPanel="onQueryTagPanel" @queryTagClick="onQueryTagClick" @search="onSearch"></query-tag>
      </el-col>
      <el-col :span="5">
        <div style="text-align: right">
          <el-button-group>
            <el-tooltip effect="dark" content="搜索">
              <el-button @click="onSearch" type="primary" icon="Search"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="重置">
              <el-button type="primary" icon="RefreshRight"
                @click="isConditionPanel ? $refs.conditionPanel.reset() : $refs.queryForm.resetFields()"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="更多">
              <el-button @click="onConditionPanel('query')" type="primary" icon="DArrowRight"></el-button>
            </el-tooltip>
          </el-button-group>
        </div>
      </el-col>
    </el-row>
    <condition-panel v-if="isConditionPanel" ref="conditionPanel" v-model="moreParm"
      :conditionColumns="
        meta.find((item) => {
          return item.type == 'main'
        }).conditionPanel
      "></condition-panel>
    <el-form v-if="!isConditionPanel" ref="queryForm" :model="queryData" label-width="100px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="名称">
            <el-input v-model="queryData['company.name']" :maxLength="128" placeholder="名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="编号">
            <el-input v-model="queryData['company.code']" :maxLength="64" placeholder="编号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="全称">
            <el-input v-model="queryData['company.fullName']" :maxLength="512" placeholder="全称" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="0" justify="end" align="top">
      <el-button type="primary" icon="Plus" @click="onCreate" v-show="permission.add">添加</el-button>
    </el-row>
    <vxe-table ref="tableRef" :id="'tableRef_' + $route.meta.routerId"
      :data="tableData" @sort-change="onSortChange"
      :tree-config="{ children: 'children', indent: 20, accordion: false, line: false, showIcon: true, iconOpen: '', iconClose: ''}">
      <vxe-column field="code" title="编号" tree-node resizable min-width="120px" align="left" header-align="center" sortable show-overflow></vxe-column>
      <vxe-column field="name" title="名称" tree-node resizable min-width="180px" align="left" header-align="center" sortable show-overflow></vxe-column>
      <vxe-column field="fullName" title="全称" tree-node resizable min-width="200px" align="left" header-align="center" sortable show-overflow></vxe-column>
      <vxe-column field="sort" title="排序" tree-node resizable width="80px" align="right" header-align="center" sortable show-overflow></vxe-column>
      <vxe-column field="chairman.name" title="董事长" tree-node resizable width="120px" align="center" header-align="center" show-overflow></vxe-column>
      <vxe-column field="manager.name" title="总经理" tree-node resizable width="120px" align="center" header-align="center" show-overflow></vxe-column>
      <vxe-column field="createBy" title="创建者" tree-node resizable width="120px" align="center" header-align="center" show-overflow :visible="false"></vxe-column>
      <vxe-column field="createDate" title="创建时间" tree-node resizable width="160px" align="right" header-align="center" sortable show-overflow :visible="false"></vxe-column>
      <vxe-column field="updateBy" title="更新者" tree-node resizable width="120px" align="center" header-align="center" show-overflow :visible="false"></vxe-column>
      <vxe-column field="updateDate" title="更新时间" tree-node resizable width="160px" align="right" header-align="center" sortable show-overflow></vxe-column>
      <vxe-column title="操作" tree-node resizable width="160px" fixed="right" align="left" header-align="center">
        <template #header>
          <span>操作</span>
          <OperationIcon @click="onExport" type="primary" content="导出excel文件" icon-name="Download"></OperationIcon>
          <OperationIcon @click="onSetting('tableRef')" type="primary" content="自定义列" icon-name="Setting"></OperationIcon>
        </template>
        <template #default="scope">
          <OperationIcon @click="onView(scope)" type="info" v-show="permission.view" content="查看" icon-name="View"></OperationIcon>
          <OperationIcon @click="onEdit(scope)" type="primary" v-show="permission.edit" content="编辑" icon-name="Edit"></OperationIcon>
          <OperationIcon @click="onCreate(scope)" type="primary" v-show="permission.add" content="添加下级" icon-name="CirclePlus"></OperationIcon>
          <OperationIcon @click="onCopy(scope)" type="primary" v-show="permission.add" content="复制" icon-name="DocumentCopy"></OperationIcon>
          <OperationIcon @click="onDelete(scope)" type="danger" v-show="permission.remove" content="删除" icon-name="Delete"></OperationIcon>
          <OperationIcon @click="onShowHistory(scope)" type="primary" v-show="permission.view" content="历史记录" icon-name="InfoFilled"></OperationIcon>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script>
import { validatenull } from '@/utils/validate'
import { treeCompany, deleteCompany } from '@/api/org/company'
import { listResourcePermission } from '@/api/admin/common/permission'
import History from '@/views/components/history'
import EditForm from './form'
import QueryTag from '@/views/components/queryTag'
import ConditionPanel from '@/views/components/conditionPanel'
import meta from './meta'
import MainUI from '@/views/components/mainUI'
import OperationIcon from '@/components/OperationIcon'

export default {
  extends: MainUI,
  components: { History, EditForm, QueryTag, ConditionPanel, OperationIcon },
  data() {
    return {
      permission: { view: false, add: false, edit: false, remove: false, export: false },
      meta,
      queryData: {
        'company.name': '', // 名称
        'company.code': '', // 编号
        'company.fullName': '' // 全称
      },
      search: {
        // 查询条件   业务表设置的筛选条件
        params: [],
        columnName: '', // 排序字段名
        order: '', // 排序
        offset: 0,
        limit: 10
      },

      tableData: [],
      tableId: 'org_company'
    }
  },
  computed: {},
  methods: {
    // 必须实现的方法 - 获取列表数据
    getList() {
      this.setLoad()
      /* 查询参数 和数据权限 */
      this.search.params = []
      if (this.isConditionPanel) {
        this.search.params = this.search.params.concat(this.compositeCondition())
      } else {
        this.search.params.push({
          columnName: 'company.name',
          queryType: 'like',
          value: !validatenull(this.queryData['company.name']) ? this.queryData['company.name'] : null
        })
        this.search.params.push({
          columnName: 'company.code',
          queryType: 'like',
          value: !validatenull(this.queryData['company.code']) ? this.queryData['company.code'] : null
        })
        this.search.params.push({
          columnName: 'company.full_name', // 数据库字段名
          queryType: 'like',
          value: !validatenull(this.queryData['company.fullName']) ? this.queryData['company.fullName'] : null
        })
      }
      // 数据权限: 公司 org_company
      this.pushDataPermissions(this.search.params, this.$route.meta.routerId, this.tableId)
      treeCompany(this.search)
        .then((responseData) => {
          if (responseData.code == 100) {
            this.tableData = responseData.data ? responseData.data : []
          } else {
            this.showMessage(responseData)
          }
          this.resetLoad()
        })
        .catch((error) => {
          this.outputError(error)
        })
    },
    // 必须实现的方法 - 搜索
    onSearch() {
      if (this.isConditionPanel) {
        this.getList()
      } else {
        this.$refs['queryForm'].validate((valid) => {
          if (valid) {
            this.getList()
          } else {
            return false
          }
        })
      }
    },
    // 必须实现的方法 - 初始化
    async pageInit() {
      this.setLoad()
      try {
        this.initOptions(this.queryModel)
        this.search.params = []
        // 数据权限: 公司 org_company
        this.pushDataPermissions(this.search.params, this.$route.meta.routerId, this.tableId)
        let [companyRespData, permissionRespData] = await Promise.all([
          treeCompany(this.search),
          listResourcePermission(this.$route.meta.routerId)
        ])
        if (companyRespData.code == 100 && permissionRespData.code == 100) {
          this.tableData = companyRespData.data ? companyRespData.data : []
          
	        this.permission.view = permissionRespData.data.find((item) => {
            return item.permission === 'company:read'
          })
          this.permission.export = permissionRespData.data.find((item) => {
            return item.permission === 'company:export'
          })

          this.permission.add = permissionRespData.data.find((item) => {
            return item.permission === 'company:create'
          })
          this.permission.edit = permissionRespData.data.find((item) => {
            return item.permission === 'company:update'
          })
          this.permission.remove = permissionRespData.data.find((item) => {
            return item.permission === 'company:delete'
          })
        } else {
          this.showMessage(permissionRespData.code != 100 ? permissionRespData : companyRespData)
        }
        this.resetLoad()
      } catch (error) {
        this.outputError(error)
      }
    },
    // 必须实现的方法 - 打开查看模式
    onView(scope) {
      this.$refs.editForm.openView(scope.row.id)
    },
    // 必须实现的方法 - 打开新增模式 
    onCreate(scope) {
      this.$refs.editForm.openAdd(scope ? scope.row : null)
    },
    // 必须实现的方法 - 打开编辑模式
    onEdit(scope) {
      this.$refs.editForm.openEdit(scope.row.id)
    },
    // 必须实现的方法 - 打开复制模式
    onCopy(scope) {
      this.$refs.editForm.openCopy(scope.row.id)
    },
    // 必须实现的方法 - 删除记录
    onDelete(scope) {
      this.$confirm('确定删除吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.setLoad()
          deleteCompany(scope.row)
            .then((responseData) => {
              if (responseData.code == 100) {
                this.getList()
                this.showMessage({
                  type: 'success',
                  msg: '删除成功'
                })
              } else {
                this.showMessage(responseData)
              }
              this.resetLoad()
            })
            .catch((error) => {
              this.outputError(error)
            })
        })
        .catch(() => {})
    },
    // 必须实现的方法 - 设置
    onSetting(tableRef) {
      this.$refs[tableRef].triggerCustomEvent(event)
    },
    // 必须实现的方法 - 导出
    onExport() {
      this.$refs.tableRef.exportData()
    },
    // 必须实现的方法 - 排序
    onSortChange(orderby) {
      if (validatenull(orderby.prop)) {
        this.search.columnName = ''
        this.search.order = ''
      } else {
        this.search.columnName = orderby.prop
        this.search.order = orderby.order
      }
      this.getList()
    },

    // 初始化自定义类型选择框选项变量，根据需要实现
    initOptions(This) {}
  },
  watch: {},
  mounted() {
    this.pageInit()
  }
}
</script> 